using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mail;

/// <summary>
/// Summary description for CommonClass
/// </summary>
public class CommonClass
{
    public static string CurrentCulture = "vi-VN";
    public static readonly string DateTimeFormatDataBase = "MM/dd/yyyy hh:mm:ss";
    public static readonly string DateTimeFormatDataBaseBE = "MM/dd/yyyy hh:mm:ss";
    public static readonly string DateTimeFormatWebsites = "dd/MM/yyyy";
    public static readonly string DateTimeFormatWebsitesFE = "dd/MM/yyyy";
    public static readonly string DateTimeFormatWebsitesBE = "dd/MM/yyyy";
    public static readonly string dbFolder = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"Photos\sanqvenus.txt";
    public static readonly string fileVisisted = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"App_Data\visited.txt";
    public static readonly string fileOnline = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"Photos\online.txt";
    public static string FolderPhotoData = AppDomain.CurrentDomain.BaseDirectory + @"Photos\";
    public static string FolderImagesData = AppDomain.CurrentDomain.BaseDirectory + @"images\";
    public static string FolderUploadData = AppDomain.CurrentDomain.BaseDirectory + @"Upload\";

    #region CreateGUI
    /// <summary>
    /// using for make id string by System.Guid
    /// </summary>
    /// <returns>id string</returns>
    public static string CreateGUI()
    {
        string rs = "";
        char replace = '-';
        char to = '_';
        try
        {
            rs = Guid.NewGuid().ToString();
            rs = rs.Replace(replace, to);
        }
        catch (Exception ex)
        {
            string mess = ex.Message.ToString();
        }
        return rs;
    }
    #endregion CreateGUI

    #region Session Method
    /// <summary>
    /// Using for Set value of variable of each form
    /// </summary>
    /// <param name="session_FormName">Ex: ss_ucSCDepartmentViewAddEdit</param>
    /// <param name="KeyName">Key of value base on each Form. Ex: _actionType</param>
    /// <param name="KeyValue">Value of Key base on each Form</param>
    public static void Session_Get_Set(string session_FormName, string KeyName, object KeyValue)
    {
        Hashtable htb = (Hashtable)HttpContext.Current.Session[session_FormName];

        if (htb == null)
            htb = new Hashtable();

        if (htb.Contains(KeyName))
            htb[KeyName] = KeyValue;
        else
            htb.Add(KeyName, KeyValue);

        HttpContext.Current.Session[session_FormName] = htb;

    }

    /// <summary>
    /// Using for get value of Key base on each Form
    /// </summary>
    /// <param name="session_FormName">Ex: ss_ucSCDepartmentViewAddEdit</param>
    /// <param name="KeyName">Key of value base on each Form. Ex: _actionType</param>
    /// <returns>Key's value</returns>
    public static object Session_Get_Set(string session_FormName, string KeyName)
    {

        Hashtable htb = (Hashtable)HttpContext.Current.Session[session_FormName];

        if (htb == null)
            return null;
        else
        {
            if (htb.Contains(KeyName))
                return htb[KeyName];
            else
                return null;
        }
    }

    /// <summary>
    /// Using for remove value of key base on each Form
    /// </summary>
    /// <param name="session_FormName">Ex: ss_ucSCDepartmentViewAddEdit</param>
    /// <param name="KeyName">Key of value base on each Form. Ex: _actionType</param>
    public static void Session_RemoveAt(string session_FormName, string KeyName)
    {
        Hashtable htb = (Hashtable)HttpContext.Current.Session[session_FormName];

        if (htb == null)
            return;
        else
        {
            if (htb.Contains(KeyName))
                htb.Remove(KeyName);
        }

        HttpContext.Current.Session[session_FormName] = htb;
    }

    /// <summary>
    /// Using for remove session on each Form
    /// </summary>
    /// <param name="session_FormName">Ex: ss_ucSCDepartmentViewAddEdit</param>
    public static void Session_Remove(string session_FormName)
    {
        if (HttpContext.Current.Session[session_FormName] != null)
            HttpContext.Current.Session.Remove(session_FormName);
    }

    #endregion Session Method

    #region encode
    public static string encodeMD5(string s)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "MD5");
    }
    public static string encodeSHA1(string s)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "SHA1");
    }
    #endregion encode

    #region date format

    public static string ConvertToDBDateFormat(string DateString)
    {
        string rs = "";
        string date = DateString;

        try
        {
            CultureInfo cti = new CultureInfo(CurrentCulture);
            DateTime dti = Convert.ToDateTime(date, cti);
            rs = dti.ToString(DateTimeFormatDataBase);
        }
        catch (Exception ex)
        {
            string mess = ex.Message.ToString();
        }
        return rs;
    }

    public static DateTime ConvertToDBDateTime(string DateString)
    {
        DateTime rs = DateTime.Now;
        string date = DateString;

        try
        {
            CultureInfo cti = new CultureInfo(CurrentCulture);

            rs = Convert.ToDateTime(date, cti);
        }
        catch (Exception ex)
        {
            string mess = ex.Message.ToString();
        }
        return rs;
    }


    #endregion

    #region UploadFile
    public static bool UploadFile(System.Web.UI.WebControls.FileUpload fileUpload, string filePath, string fileName)
    {
        bool bResult = false;
        try
        {
            if (fileUpload.FileName.Trim() != "")
            {
                string sFileUpload = filePath + fileName;

                Directory.CreateDirectory(filePath);
                fileUpload.PostedFile.SaveAs(sFileUpload);
            }
            bResult = true;
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            bResult = false;
        }
        return bResult;
    }
    public static bool UploadFile(System.Web.UI.HtmlControls.HtmlInputFile pFulCtrl, string pFilePath, string pFileName)
    {
        bool bResult = false;
        try
        {
            if (pFulCtrl.Value != "")
            {
                string sFileUpload = pFilePath + pFileName;

                Directory.CreateDirectory(pFilePath);
                pFulCtrl.PostedFile.SaveAs(sFileUpload);
            }
            bResult = true;
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            bResult = false;
        }
        return bResult;
    }
    public static bool DeleteFile(string pPath)
    {
        bool bResult = true;
        try
        {
            if (System.IO.File.Exists(pPath))
            {
                System.IO.File.Delete(pPath);
            }
            bResult = true;
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            bResult = false;
        }
        return bResult;
    }
    public static bool DeleteFolder(string pPath)
    {
        bool bResult = true;
        try
        {
            if (System.IO.Directory.Exists(pPath))
            {
                System.IO.Directory.Delete(pPath, true);
            }
            bResult = true;
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            bResult = false;
        }
        return bResult;
    }
    #region CopyFileToFolder
    /// <summary>
    /// using for Copy file from folder To Folder
    /// </summary>
    /// <param name="sOldDirPath"> Physical Path of current folder</param>
    /// <param name="sNewDirPath"> Physical Path of new folder</param>
    /// <returns>bool</returns>
    /// 
    public static bool CopyFileToFolder(string SourcePath, string DestinationPath, string FileName)
    {
        try
        {
            File.Copy(SourcePath + FileName, DestinationPath + FileName, true);
            return true;
        }
        catch (Exception ex)
        {
            string mess = ex.Message.ToString();
            return false;
        }
    }
    #endregion
    /// <summary>
    /// Using for get file extension (Ex: 'filename.txt' --> '.txt', 'foldername\filename.cs' --> '.cs')
    /// </summary>
    /// <param name="pFileName">type string: filename</param>
    /// <returns></returns>
    public static string getFileExtendtion(string pFileName)
    {
        string rs = "";
        int i = pFileName.LastIndexOf(".");
        if (i > 0)
        {
            rs = pFileName.Substring(i);
        }
        return rs;
    }

    /// <summary>
    /// Using for get file name (Ex: 'C:\foldername\filename.txt' --> 'filename.txt')
    /// </summary>
    /// <param name="pFilename">type string: filename</param>
    /// <returns></returns>
    public static string getFileName(string pFilename)
    {
        string rs = "";
        int i = pFilename.LastIndexOf(@"\");
        if (i > 0)
        {
            rs = pFilename.Substring(i + 1, pFilename.Length - i - 1);
        }
        else
            rs = pFilename;
        return rs;
    }
    #endregion UploadFile

    #region Counter

    public static int IncreaseCounter(string filePath, int increase)
    {
        int counter = -1;
        string error = "";
        try
        {
            // create file if it's not exsits
            if (!System.IO.File.Exists(filePath))
            {
                // create file and write default value to new file
                System.IO.File.WriteAllText(filePath, "0");
            }

            // open file to read the counter value
            StreamReader sr = new StreamReader(filePath);
            error = sr.ReadLine();
            sr.Close();
            sr.Dispose();
            
            // increase counter value
            counter = Convert.ToInt32(error);
            counter++;

            // write counter value to file
            StreamWriter sw = new StreamWriter(filePath, false); // the file will be overwritten
            sw.WriteLine(counter.ToString());
            sw.Close();
            sw.Dispose();
        }
        catch(IOException ioex)
        {
            error = ioex.Message.ToString();
            counter = -1;
        }
        catch(Exception ex)
        {
            error = ex.Message.ToString();
            counter = -1;
        }
        return counter;
    }

    public static int ReadCounter(string filePath)
    {
        int counter = -1;
        string error = "";
        try
        {
            // open file to read the counter value
            StreamReader sr = new StreamReader(filePath);
            error = sr.ReadLine();
            sr.Close();
            
            // get counter value
            counter = Convert.ToInt32(error);
        }
        catch (Exception ex)
        {
            error = ex.ToString();
            counter = -1;
        }

        return counter;
    }

    #endregion Counter

    #region validateIsUserName
    public static bool validateStringByStringAllowCharacter(string strInputString, string strAllowCharacter)
    {
        string sTemp;
        for (int i = 0; i < strInputString.Length; i++)
        {
            sTemp = strInputString.Substring(i, 1);
            if (strAllowCharacter.IndexOf(sTemp, 0) == -1)
                return false;
        }
        return true;
    }
    public static bool validateIsUserName(string txtText)
    {

        int MinLength = 0;
        int MaxLength = 25;
        string strAllow_Username_Character = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
        // validate
        bool bolReturn = true;

        // validate null
        if (txtText == "")
        {
            bolReturn = false;
        }
        // validate SQL Injection
        else if (txtText.IndexOf("--", 0) >= 0)
        {
            bolReturn = false;
        }
        else if (txtText.IndexOf("=", 0) >= 0)
        {
            bolReturn = false;
        }
        else if (txtText.IndexOf(";", 0) >= 0)
        {
            bolReturn = false;
        }
        // validate by allow characters
        else if (validateStringByStringAllowCharacter(txtText, strAllow_Username_Character) == false)
        {
            bolReturn = false;
        }
        // validate min length
        else if (txtText.Length < MinLength)
        {
            bolReturn = false;
        }
        // validate max length
        else if (txtText.Length > MaxLength)
        {
            bolReturn = false;
        }
        return bolReturn;
    }
    #endregion

    #region function Send Mail
    /// <summary>
    /// Send a email using SMTP server
    /// </summary>
    /// <param name="strFrom">type string: the e-mail address of the sender.</param>
    /// <param name="strTo">type string: a semicolon-delimited list of recipient e-mail addresses.</param>
    /// <param name="strSubject">type string: the subject line of the e-mail message.</param>
    /// <param name="strBody">type string: the body of the e-mail message.</param>
    /// <param name="strSMTPServer">type string: SMTP server</param>
    /// <returns>bool true: send successful; false: unsuccessful</returns>
    public static bool SendMail(string strFrom, string strTo, string strSubject, string strBody, string strSMTPServer)
    {
        bool bResult = true;
        try
        {
            MailMessage objMessage = new MailMessage();
            objMessage.From = strFrom;
            objMessage.To = strTo;
            objMessage.Subject = strSubject;
            objMessage.BodyFormat = MailFormat.Html;
            objMessage.Body = strBody;
            objMessage.BodyEncoding = Encoding.GetEncoding("utf-8");
            objMessage.BodyEncoding.GetDecoder();

            string s = GetValueFromConfiguration("IsLocalhost");
            bool b = true;
            try
            {
                b = Convert.ToBoolean(s);
            }
            catch
            {
                b = false;
            }

            if (b)
                SmtpMail.SmtpServer = strSMTPServer;
            else
                SmtpMail.SmtpServer.Insert(0, strSMTPServer);
            SmtpMail.Send(objMessage);

            objMessage = null;

            bResult = true;
        }
        catch (Exception exc)
        {
            string mess = exc.Message;
            bResult = false;
        }
        return bResult;
    }

    /// <summary>
    /// Send a email using SMTP server
    /// </summary>
    /// <param name="strFrom">type string: the e-mail address of the sender.</param>
    /// <param name="strTo">type string: a semicolon-delimited list of recipient e-mail addresses.</param>
    /// <param name="strSubject">type string: the subject line of the e-mail message.</param>
    /// <param name="strBody">type string: the body of the e-mail message.</param>
    /// <param name="arrFileAttach">type ArrayList: list of filename attach</param>
    /// <param name="strSMTPServer">type string: SMTP server</param>
    /// <returns>bool true: send successful; false: unsuccessful</returns>
    public static bool SendMail(string strFrom, string strTo, string strSubject, string strBody, ArrayList arrFileAttach, string strSMTPServer)
    {
        bool bResult = true;
        try
        {
            MailMessage objMessage = new MailMessage();
            objMessage.From = strFrom;
            objMessage.To = strTo;
            objMessage.Subject = strSubject;
            objMessage.BodyFormat = MailFormat.Html;
            objMessage.Body = strBody;
            objMessage.BodyEncoding = Encoding.GetEncoding("utf-8");
            objMessage.BodyEncoding.GetDecoder();

            if (arrFileAttach != null)
            {
                MailAttachment mailAttach = null;
                foreach (string sFilename in arrFileAttach)
                {
                    mailAttach = new MailAttachment(sFilename);
                    objMessage.Attachments.Add(mailAttach);
                }
            }

            SmtpMail.SmtpServer = strSMTPServer;
            //SmtpMail.SmtpServer.Insert(0,strSMTPServer);
            SmtpMail.Send(objMessage);

            objMessage = null;

            bResult = true;
        }
        catch (Exception exc)
        {
            string mess = exc.Message;
            bResult = false;
        }
        return bResult;
    }

    /// <summary>
    /// Send a email using SMTP server
    /// </summary>
    /// <param name="strFrom">type string: the e-mail address of the sender.</param>
    /// <param name="strTo">type string: a semicolon-delimited list of recipient e-mail addresses.</param>
    /// <param name="strSubject">type string: the subject line of the e-mail message.</param>
    /// <param name="strBody">type string: the body of the e-mail message.</param>
    /// <param name="arrFileAttach">type ArrayList: list of filename attach</param>
    /// <param name="strSMTPServer">type string: SMTP server</param>
    /// <returns>bool true: send successful; false: unsuccessful</returns>
    public static bool SendMail(string strFrom, string strTo, string strCc, string strSubject, string strMessages, string strSMTPServer)
    {
        bool bResult = true;
        try
        {
            MailMessage objMessage = new MailMessage();
            objMessage.From = strFrom;
            objMessage.To = strTo;
            objMessage.Subject = strSubject;
            objMessage.Cc = strCc;
            objMessage.BodyFormat = MailFormat.Html;
            objMessage.Body = strMessages;
            objMessage.BodyEncoding = Encoding.GetEncoding("utf-8");
            objMessage.BodyEncoding.GetDecoder();

            string s = GetValueFromConfiguration("IsLocalhost");
            bool b = true;
            try
            {
                b = Convert.ToBoolean(s);
            }
            catch
            {
                b = false;
            }

            if (b)
                SmtpMail.SmtpServer = strSMTPServer;
            else
                SmtpMail.SmtpServer.Insert(0, strSMTPServer);
            SmtpMail.Send(objMessage);

            objMessage = null;

            bResult = true;
        }
        catch (Exception exc)
        {
            string mess = exc.Message;
            bResult = false;
        }
        return bResult;
    }
    #endregion

    #region send email with lib
    #endregion send email with lib

    #region validate email
    /// <summary>
    /// Using for validate email address
    /// </summary>
    /// <param name="pEmailAddress">type string: email input</param>
    /// <returns>true if email valid, else return false</returns>
    public static bool validateEmail(string pEmailAddress)
    {
        // validate
        bool bReturn = true;

        Regex emailregex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

        if (emailregex.IsMatch(pEmailAddress) == true)
            bReturn = true;
        else
            bReturn = false;

        return bReturn;
    }
    #endregion

    #region Configuration
    public static string GetValueFromConfiguration(string configurationName)
    {
        string rs = "";
        try
        {
            if (ConfigurationSettings.AppSettings[configurationName] != null)
                rs = ConfigurationSettings.AppSettings[configurationName].ToString();
            else
                rs = "";
        }
        catch
        {
            rs = "";
        }
        return rs;
    }
    public static bool GetValueFromConfiguration(string configurationName, bool defaultValue)
    {
        bool rs = defaultValue;
        try
        {
            if (ConfigurationSettings.AppSettings[configurationName] != null)
                rs = Convert.ToBoolean(ConfigurationSettings.AppSettings[configurationName]);
            else
                rs = defaultValue;
        }
        catch
        {
            rs = defaultValue;
        }
        return rs;
    }
    #endregion Configuration
}
